﻿using JaegerDemo.DService.Host.Models;
using JaegerDemo.Events;
using MassTransit;
using OpenTracing;
using OpenTracing.Propagation;
using OpenTracing.Tag;

namespace JaegerDemo.DService.Host.EventHandlers;

public class ValueCreatedIntegrationEventHandler : IConsumer<ValueCreatedIntegrationEvent>
{
    private readonly DServiceDbContext _dbContext;
    private readonly ITracer _tracer;

    public ValueCreatedIntegrationEventHandler(DServiceDbContext dbContext, ITracer tracer)
    {
        _dbContext = dbContext;
        _tracer = tracer;
    }

    public async Task Consume(ConsumeContext<ValueCreatedIntegrationEvent> context)
    {
        using var scope = TracingExtension.StartServerSpan(_tracer, context.Message.TrackingKeys, "Value created integration event handler");

        var value = context.Message.Value;
        Console.WriteLine($"Value:{value}");
        await _dbContext.ValueAggregates.AddAsync(new ValueAggregate(value));
        await _dbContext.SaveChangesAsync();
    }
}

public static class TracingExtension
{
    public static IScope StartServerSpan(ITracer tracer, Dictionary<string, string> headers, string operationName)
    {
        ISpanBuilder spanBuilder;
        try
        {
            ISpanContext parentSpanCtx = tracer.Extract(BuiltinFormats.TextMap, new TextMapExtractAdapter(headers));
            spanBuilder = tracer.BuildSpan(operationName);
            if (parentSpanCtx != null)
            {
                spanBuilder = spanBuilder.AsChildOf(parentSpanCtx);
            }
        }
        catch (Exception)
        {
            spanBuilder = tracer.BuildSpan(operationName);
        }

        return spanBuilder.WithTag(Tags.SpanKind, Tags.SpanKindConsumer).StartActive(true);
    }
}